<template>
  <div style="display: inline-block;margin: 0 10px 0 10px">
    <el-button
      :type="type"
      :disabled="disabled"
      :plain="plain"
      :icon="icon"
      :loading="exportLoading"
      @click="downLoad"
    >{{ text }}</el-button>
  </div>
</template>

<script>

import axios from 'axios'

export default {
  name: 'DownloadButton',
  props: {
    params: {
      type: Object,
      default() {
        return {}
      }
    },
    path: { // url地址
      default: '',
      type: String
    },
    type: {
      type: String,
      default() {
        return 'primary'
      }
    },
    text: {
      type: String,
      default() {
        return '导出'
      }
    },
    icon: {
      type: String,
      default() {
        return ''
      }
    },
    plain: {
      type: Boolean,
      default() {
        return false
      }
    },
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    return {
      exportLoading: false
    }
  },
  methods: {
    downLoad() {
      this.exportLoading = true
      axios({
        method: 'post',
        url: this.path,
        headers: {
          authorization: window.sessionStorage.getItem('authorization')
        },
        data: this.params,
        responseType: 'blob'
      }).then(res => {
        if (res) {
          const link = document.createElement('a')
          const contentType = this.params.contentType ? this.params.contentType : 'application/vnd.ms-excel'
          const blob = new Blob([res.data], { type: contentType })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', this.params.fileName + `.xlsx`)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.exportLoading = false
        }
      }).finally(() => {
        this.exportLoading = false
      })
    }
  }
}
</script>

<style scoped>

</style>
